import base64
from Crypto.Cipher import AES
import datetime
import json
import logging
import requests
from rest_framework import exceptions
import urllib3

from NewStudentManageSys.settings.dev import WX_CONFIG, WX_PC_CONFIG, WX_SMART_CONFIG
from message.models import MassMessaging, StudentMessage
from order.models import Order
from record.models import ChannelRecord
from student_info.models import StudentInfo, Schoolmate
from utils.common.token import generate_token
from tools.redis_tools.redis_server import redis_client, redis_cli_wx
from multiprocessing.dummy import Pool
from utils.common.common import send_images_by_wx

logger = logging.getLogger('django')


class WXBizDataCrypt(object):
    def __init__(self, appId, sessionKey):
        self.appId = appId
        self.sessionKey = sessionKey

    def decrypt(self, encryptedData, iv):
        # base64 decode
        sessionKey = base64.b64decode(self.sessionKey)
        encryptedData = base64.b64decode(encryptedData)
        iv = base64.b64decode(iv)

        cipher = AES.new(sessionKey, AES.MODE_CBC, iv)
        a = cipher.decrypt(encryptedData)
        b = self._unpad(a)
        decrypted = json.loads(b)
        if decrypted['watermark']['appid'] != self.appId:
            raise Exception('Invalid Buffer')

        return decrypted
        # pass

    def _unpad(self, s):
        return s[:-ord(s[len(s) - 1:])]


class WxInterface():
    def __init__(self):
        self.appid = WX_CONFIG.get('APP_ID')
        self.secret = WX_CONFIG.get('APP_SECRET')
        self.applet_appid = WX_SMART_CONFIG.get('APP_ID')
        self.applet_secret = WX_SMART_CONFIG.get('APP_SECRET')
        self.pc_appid = WX_PC_CONFIG.get('APP_ID')
        self.pc_secret = WX_PC_CONFIG.get('APP_SECRET')

    def get_unionid_by_openid(self, instance, openid):
        access_token = self.get_grant_token()
        url = f'https://api.weixin.qq.com/cgi-bin/user/info?access_token={access_token}&openid={openid}&lang=zh_CN'
        response = requests.get(url=url)
        if response.status_code != 200:
            logger.info('X' * 70)
            logger.info(response.text)
            logger.info('X' * 70)
            raise exceptions.ValidationError('连接微信服务器异常')
        res = response.json()
        if res.get('unionid'):
            instance.unionid = res.get('unionid')
            instance.save()
            return {'is_get_unionid': True}
        return {'is_get_unionid': False}

    # 微信公众号code认证
    def code_authorize(self, code, openid, channel, is_schoolmate):
        # 供前端测试使用(1)
        # args : code , openid(选择性传)，如果传入openid则是进行非静默授权
        # 1.静默授权 code 得到openid,创建学生用户，填4个信息更新学生信息
        # 2.非静默(前端触发) code,openid -> openid,unionid
        # 1.新用户进来静默授权获取openid，判断用户是否填写4个资料，如果没有则跳转到4个资料页面，点击提交按钮，更新用户信息，在进行非静默授权，
        # 用户同意则进入首页，但是用户不同意呢？进入哪个页面？
        # 用户第二次进入，先静默看该学生是否有unionid，如果没有则非静默授权，如果有则直接进入首页
        if code == '888888':
            user_info = StudentInfo.objects.filter(id=20800).first()
            # 看该用户是否填写了4个基本信息
            is_new_student = True if not user_info.name else False
            # is_new_student = True
            has_unionid = True if user_info.unionid else False
            token = generate_token(user_info.id, 1)
            if user_info.last_login_time:
                message_list = MassMessaging.objects.filter(create_time__gt=user_info.last_login_time)
                if message_list:
                    for message in message_list.values('message', 'user_id'):
                        StudentMessage.objects.create(student_id=user_info.id, message=message['message'],
                                                      user_id=message['user_id'])
            user_info.last_login_time = datetime.datetime.now()
            user_info.save()
            if is_schoolmate:
                schoolmate = Schoolmate.objects.filter(name=user_info.name, cschool=user_info.cschool,
                                                       wechat=user_info.wechat, email=user_info.email)
                if not schoolmate:
                    order_status = Order.objects.filter(student=user_info).values_list('order_status', flat=True)
                    if 'CONFIRMED' in order_status:
                        level = 'LV.3'
                    else:
                        level = 'LV.2'
                    Schoolmate.objects.create(student=user_info, name=user_info.name, cschool=user_info.cschool,
                                              wechat=user_info.wechat, email=user_info.email, grade=user_info.grade,
                                              level=level)
                else:
                    school_mate = schoolmate.filter(student__isnull=True)
                    if school_mate:
                        school_mate.update(student=user_info)
            return {'user_id': user_info.id, 'token': token, 'is_new_student': is_new_student,
                    'has_unionid': has_unionid, 'openid': user_info.base_openid}
        user_id = redis_client.get_instance(code)
        if user_id:
            user_info = StudentInfo.objects.filter(id=user_id).first()
            if user_info.last_login_time:
                message_list = MassMessaging.objects.filter(create_time__gt=user_info.last_login_time)
                if message_list:
                    for message in message_list.values('message', 'user_id'):
                        StudentMessage.objects.create(student_id=user_info.id, message=message['message'],
                                                      user_id=message['user_id'])
            user_info.last_login_time = datetime.datetime.now()
            user_info.save()
            token = generate_token(user_info.id, 1)
            # 判断该学生是否有unionid
            has_unionid = True if user_info.unionid else False
            is_new_student = True if not user_info.name else False
            if is_schoolmate:
                schoolmate = Schoolmate.objects.filter(student=user_info)
                if not schoolmate:
                    order_status = Order.objects.filter(student=user_info).values_list('order_status', flat=True)
                    if 'CONFIRMED' in order_status:
                        level = 'LV.3'
                    else:
                        level = 'LV.2'
                    Schoolmate.objects.create(student=user_info, name=user_info.name, cschool=user_info.cschool,
                                              wechat=user_info.wechat, email=user_info.email, grade=user_info.grade,
                                              level=level)
                else:
                    school_mate = schoolmate.filter(student__isnull=True)
                    if school_mate:
                        school_mate.update(student=user_info)
            return {'user_id': user_info.id, 'token': token, 'is_new_student': is_new_student,
                    'has_unionid': has_unionid, 'openid': user_info.base_openid}
        url = "https://api.weixin.qq.com/sns/oauth2/access_token"
        params = {
            'appid': self.appid,
            'secret': self.secret,
            'code': code,
            'grant_type': 'authorization_code'
        }
        requests.packages.urllib3.disable_warnings()
        response = requests.get(url=url, params=params, verify=False)
        if response.status_code != 200:
            logger.info('X' * 70)
            logger.info(response.text)
            logger.info('X' * 70)
            raise exceptions.ValidationError('连接微信服务器异常')
        res = response.json()
        # logger.info(res)
        # redis_client.set_instance(f'{self.appid}_access_token', res.get('access_token'), 2 * 60 * 60 - 100)
        # 有两种情况 1.存在unionid和openid(非静默) 2.只存在openid(静默，和非静默的openid不同)
        if res.get('unionid'):
            # 非静默，用户肯定已经存在
            user_info = StudentInfo.objects.filter(base_openid=openid).first()
            user_info.unionid = res.get('unionid')
            user_info.userinfo_openid = res.get('openid')
            if user_info.last_login_time:
                message_list = MassMessaging.objects.filter(create_time__gt=user_info.last_login_time)
                if message_list:
                    for message in message_list.values('message', 'user_id'):
                        StudentMessage.objects.create(student_id=user_info.id, message=message['message'],
                                                      user_id=message['user_id'])
            user_info.last_login_time = datetime.datetime.now()
            user_info.save()
            token = generate_token(user_info.id, 1)
            redis_client.set_instance(code, user_info.id, default_valid_time=60 * 60 * 2)
            if is_schoolmate:
                schoolmate = Schoolmate.objects.filter(student=user_info)
                if not schoolmate:
                    order_status = Order.objects.filter(student=user_info).values_list('order_status', flat=True)
                    if 'CONFIRMED' in order_status:
                        level = 'LV.3'
                    else:
                        level = 'LV.2'
                    Schoolmate.objects.create(student=user_info, name=user_info.name, cschool=user_info.cschool,
                                              wechat=user_info.wechat, email=user_info.email, grade=user_info.grade,
                                              level=level)
                else:
                    school_mate = schoolmate.filter(student__isnull=True)
                    if school_mate:
                        school_mate.update(student=user_info)
            return {'user_id': user_info.id, 'token': token, 'is_new_student': False,
                    'has_unionid': True, 'openid': user_info.base_openid}
        elif res.get('openid'):
            # 静默，首先查询数据库中是否存在该用户信息
            user_info = StudentInfo.objects.filter(base_openid=res['openid']).first()
            if not user_info:
                # 如果用户不存在，则向数据库插入数据，肯定不存在openid
                user_info = StudentInfo.objects.create(base_openid=res['openid'],
                                                       last_login_time=datetime.datetime.now())
                # 将学生id和渠道对应关系记录到表
                if channel:
                    ChannelRecord.objects.create(student_id=user_info.id, channel_id=channel)
            else:
                # 如果用户存在，更新用户信息
                if user_info.last_login_time:
                    message_list = MassMessaging.objects.filter(create_time__gt=user_info.last_login_time)
                    if message_list:
                        for message in message_list.values('message', 'user_id'):
                            StudentMessage.objects.create(student_id=user_info.id, message=message['message'],
                                                          user_id=message['user_id'])
                user_info.last_login_time = datetime.datetime.now()
                user_info.save()
                # 处理系统数据未迁移问题
                if not user_info.name and channel:
                    ChannelRecord.objects.create(student_id=user_info.id, channel_id=channel)
                if is_schoolmate:
                    schoolmate = Schoolmate.objects.filter(student=user_info)
                    if not schoolmate:
                        order_status = Order.objects.filter(student=user_info).values_list('order_status', flat=True)
                        if 'CONFIRMED' in order_status:
                            level = 'LV.3'
                        else:
                            level = 'LV.2'
                        Schoolmate.objects.create(student=user_info, name=user_info.name, cschool=user_info.cschool,
                                                  wechat=user_info.wechat, email=user_info.email, grade=user_info.grade,
                                                  level=level)
                    else:
                        school_mate = schoolmate.filter(student__isnull=True)
                        if school_mate:
                            school_mate.update(student=user_info)
            is_new_student = True if not user_info.name else False
            has_unionid = True if user_info.unionid else False
            # has_unionid = False
            token = generate_token(user_info.id, 1)
            # code不是每次都变吗? 还可以缓存? 原因是页面刷新时候，前端的请求的url没有改变还会带着之前的code请求微信认证的接口
            redis_client.set_instance(code, user_info.id, default_valid_time=60 * 60 * 2)
            # redis_client.set_instance(f'authorize_{user_info.id}', res.get('access_token'))
            return {'user_id': user_info.id, 'token': token, 'is_new_student': is_new_student,
                    'has_unionid': has_unionid, 'openid': user_info.base_openid}
        else:
            logger.info('X' * 70)
            logger.info(response.text)
            logger.info('X' * 70)
            raise exceptions.ValidationError('微信认证异常： %s' % json.dumps(res))

    def pc_code_authorize(self, code):
        """ pc端code认证"""
        if code == '888888':
            # 供前端测试使用(2964)
            user_info = StudentInfo.objects.filter(id=2964).first()
            token = generate_token(user_info.id, 1)
            return {'user_id': user_info.id, 'token': token, 'student_status': user_info.student_status}
        user_id = redis_client.get_instance(code)
        if user_id:
            user_info = StudentInfo.objects.filter(id=user_id).first()
            user_info.last_login_time = datetime.datetime.now()
            user_info.save()
            token = generate_token(user_info.id, 1)
            return {'user_id': user_info.id, 'token': token, 'student_status': user_info.student_status}
        url = "https://api.weixin.qq.com/sns/oauth2/access_token"
        params = {
            'appid': self.pc_appid,
            'secret': self.pc_secret,
            'code': code,
            'grant_type': 'authorization_code'
        }
        logger.info(code)
        response = requests.get(url=url, params=params, verify=False)
        logger.info(response)
        if response.status_code != 200:
            logger.info('X' * 70)
            logger.info(response.text)
            logger.info('X' * 70)
            raise exceptions.ValidationError('连接微信服务器异常')
        res = response.json()
        logger.info(res)
        logger.info('*' * 65)
        logger.info(response.text)
        if not (res.get('openid') and res.get('access_token')):
            raise exceptions.ValidationError('微信认证异常： %s' % json.dumps(res))
        url = "https://api.weixin.qq.com/sns/userinfo"
        params = {
            'access_token': res.get('access_token'),
            'openid': res.get('openid'),
            'lang': 'zh_CN'
        }
        response = requests.get(url=url, params=params, verify=False)
        if response.status_code != 200:
            logger.info('X' * 70)
            logger.info(response.text)
            logger.info('X' * 70)
            raise exceptions.ValidationError('连接微信服务器异常')
        res = response.json()
        logger.info('*' * 65)
        logger.info(response.text)
        if res.get('unionid'):
            # 首先查询数据库中是否存在该用户信息
            user_info = StudentInfo.objects.filter(unionid=res['unionid']).first()
            if not user_info:
                # 如果用户不存在，返回给前端
                return {'unionid': res['unionid'], 'headimgurl': res['headimgurl']}
            else:
                # 如果用户存在，更新用户信息
                user_info.last_login_time = datetime.datetime.now()
                user_info.save()
            token = generate_token(user_info.id, 1)
            redis_client.set_instance(code, user_info.id)
            return {'user_id': user_info.id, 'token': token, 'student_status': user_info.student_status,
                    'headimgurl': res['headimgurl']}
        else:
            logger.info('X' * 70)
            logger.info(response.text)
            logger.info('X' * 70)
            raise exceptions.ValidationError('微信认证异常： %s' % json.dumps(res))

    def pc_info_save(self, code, unionid, pc_code):
        """新老用户unionid与openid对应保存"""
        user_id = redis_client.get_instance(code)
        if user_id:
            user_info = StudentInfo.objects.filter(id=user_id).first()
            user_info.last_login_time = datetime.datetime.now()
            user_info.save()
            token = generate_token(user_info.id, 1)
            return {'user_id': user_info.id, 'token': token, 'student_status': user_info.student_status}
        url = "https://api.weixin.qq.com/sns/oauth2/access_token"
        params = {
            'appid': self.appid,
            'secret': self.secret,
            'code': code,
            'grant_type': 'authorization_code'
        }
        response = requests.get(url=url, params=params, verify=False)
        if response.status_code != 200:
            logger.info('X' * 70)
            logger.info(response.text)
            logger.info('X' * 70)
            raise exceptions.ValidationError('连接微信服务器异常')
        res = response.json()
        logger.info('*' * 65)
        logger.info(response.text)
        if res.get('openid'):
            logger.info(res['openid'])
            # 首先查询数据库中是否存在该用户信息
            user_info = StudentInfo.objects.filter(openid=res['openid']).first()
            if not user_info:
                # 如果用户不存在，则向数据库插入数据
                user_info = StudentInfo.objects.create(unionid=unionid, openid=res['openid'],
                                                       last_login=datetime.datetime.now())
            else:
                # 如果用户存在，更新用户信息
                user_info.last_login_time = datetime.datetime.now()
                user_info.unionid = unionid
                user_info.save()
            token = generate_token(user_info.id, 1)
            redis_client.set_instance(pc_code, user_info.id)
            return {'user_id': user_info.id, 'token': token, 'student_status': user_info.student_status}
        else:
            logger.info('X' * 70)
            logger.info(response.text)
            logger.info('X' * 70)
            raise exceptions.ValidationError('微信认证异常： %s' % json.dumps(res))

    def check_unionid(self, unionid):
        """核实unionid"""
        user_info = StudentInfo.objects.filter(unionid=unionid).first()
        if not user_info:
            return
        else:
            user_info.last_login_time = datetime.datetime.now()
            user_info.save()
        token = generate_token(user_info.id, 1)
        return {'user_id': user_info.id, 'token': token, 'student_status': user_info.student_status}

    def _code_authorize(self, code):
        # 供前端测试使用
        if code == '888888':
            user_info = StudentInfo.objects.filter(id=2964).first()
            token = generate_token(user_info.id, 1)
            return {'user_id': user_info.id, 'token': token, 'student_status': user_info.student_status}
        user_id = redis_client.get_instance(code)
        if user_id:
            user_info = StudentInfo.objects.filter(id=user_id).first()
            user_info.last_login_time = datetime.datetime.now()
            user_info.save()
            token = generate_token(user_info.id, 1)
            return {'user_id': user_info.id, 'token': token, 'student_status': user_info.student_status}
        url = "https://api.weixin.qq.com/sns/oauth2/access_token"
        params = {
            'appid': self.appid,
            'secret': self.secret,
            'code': code,
            'grant_type': 'authorization_code'
        }
        response = requests.get(url=url, params=params, verify=False)
        if response.status_code != 200:
            logger.info('X' * 70)
            logger.info(response.text)
            logger.info('X' * 70)
            raise exceptions.ValidationError('连接微信服务器异常')
        res = response.json()
        logger.info('*' * 65)
        logger.info(response.text)
        if res.get('unionid'):
            # 首先查询数据库中是否存在该用户信息
            user_info = StudentInfo.objects.filter(openid=res['unionid']).first()
            if not user_info:
                # 如果用户不存在，则向数据库插入数据
                user_info = StudentInfo.objects.create(openid=res['openid'], unionid=res['unionid'],
                                                       last_login=datetime.datetime.now())
            else:
                # 如果用户存在，更新用户信息
                user_info.last_login_time = datetime.datetime.now()
                user_info.save()
            token = generate_token(user_info.id, 1)
            redis_client.set_instance(code, user_info.id)
            return {'user_id': user_info.id, 'token': token, 'student_status': user_info.student_status}
        else:
            logger.info('X' * 70)
            logger.info(response.text)
            return {'openid': res['openid']}

    def get_grant_token(self):
        # access_token是公众号的全局唯一接口调用凭据，公众号调用各接口时都需使用access_token。
        # 开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有
        # 效期目前为2个小时，需定时刷新，重复获取将导致上次获取的access_token失效。
        """获取微信access_token"""
        access_token = redis_client.get_instance('%s_access_token' % self.appid)
        if access_token:
            return access_token
        url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (
            self.appid, self.secret)
        response = requests.get(url)
        res_data = response.json()
        logger.info(res_data)
        redis_client.set_instance('%s_access_token' % self.appid, res_data['access_token'],
                                  default_valid_time=(2 * 60 * 60 - 100))
        return res_data['access_token']

    def applet_code_authorize(self, code):
        user_id = redis_client.get_instance(code)
        if user_id:
            user_info = StudentInfo.objects.filter(id=user_id).first()
            user_info.last_login_time = datetime.datetime.now()
            user_info.save()
            token = generate_token(user_info.id, 1)
            return {'user_id': user_info.id, 'token': token, 'student_status': user_info.student_status}
        url = "https://api.weixin.qq.com/sns/jscode2session"
        params = {
            'appid': self.applet_appid,
            'secret': self.applet_secret,
            'js_code': code,
            'grant_type': 'authorization_code'
        }
        response = requests.get(url=url, params=params, verify=False)
        if response.status_code != 200:
            logger.info(response.text)
            raise exceptions.ValidationError('连接微信服务器异常')
        res = response.json()
        if res.get('openid') and res.get('session_key'):
            # 首先查询数据库中是否存在该用户信息
            user_info = StudentInfo.objects.filter(applet_openid=res['openid']).first()
            if not user_info:
                # 如果用户不存在，则向数据库插入数据
                # user_info = StudentInfo.objects.create(applet_openid=res['openid'], last_login=datetime.datetime.now())
                # user_info.save()
                redis_client.set_instance(res['openid'], res['session_key'])
                return {'openid': res['openid']}
            else:
                # 如果用户存在，更新用户信息
                user_info.last_login_time = datetime.datetime.now()
                redis_client.set_instance(code, user_info.id)
                user_info.save()
            token = generate_token(user_info.id, 1)
            redis_client.set_instance(code, user_info.id)
            return {'user_id': user_info.id, 'token': token, 'student_status': user_info.student_status}
        else:
            logger.info(response.text)
            raise exceptions.ValidationError('微信认证异常： %s' % res)

    # 调用小程序接口向用户发送模板消息
    def send_template_message(self, params):
        access_token = self.get_grant_token()
        url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token
        response = requests.post(url=url, data=json.dumps(params), headers={'Content-Type': 'application/json'})
        if response.status_code != 200:
            logger.info('WxInterface code_authorize response: %s' % response.text)
            raise exceptions.ValidationError('连接微信服务器异常')
        res = response.json()
        logger.info('*' * 25 + 'send template message' + '*' * 25)
        logger.info(res)
        return

    # 调用微信接口向用户发送模板消息
    def send_template_inform(self, params):
        # access_token = self.get_grant_token()  # TODO 生产环境要更改过来
        access_token = self.get_grant_token_wx()
        # access_token = '39_OVSbpoCI9JUhKeNRyegYFYwb_60BdPFGovO12dUyfVA5wJUg73TaMJ0FSumyYsNQQ6GWBnbwcbTzShXyefOLMnqmUw7cvbvINCHX8ceBm4cRW62nqJpfRO5cQzDEqJvdS6U8_mBvvANTYeYVYKMhAJAGSU'
        url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s' % access_token
        response = requests.post(url=url, data=json.dumps(params), headers={'Content-Type': 'application/json'})
        if response.status_code != 200:
            logger.info('WxInterface code_authorize response: %s' % response.text)
            raise exceptions.ValidationError('连接微信服务器异常')
        res = response.json()
        logger.info('*' * 25 + 'send template message' + '*' * 25)
        logger.info(res)
        return response

    def get_grant_token_wx(self):
        # access_token是公众号的全局唯一接口调用凭据，公众号调用各接口时都需使用access_token。
        # 开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有
        # 效期目前为2个小时，需定时刷新，重复获取将导致上次获取的access_token失效。
        """获取微信access_token"""
        access_token = redis_cli_wx.get_instance('student_sys.access_token')
        if access_token:
            return access_token
        url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (
            self.appid, self.secret)
        response = requests.get(url)
        res_data = response.json()
        logger.info(res_data)
        redis_cli_wx.set_instance('student_sys.access_token', res_data['access_token'],
                                  default_valid_time=(2 * 60 * 60 - 100))
        return res_data['access_token']

    def send_text_message(self, openid, content):
        """发送文本消息"""
        url = "https://api.weixin.qq.com/cgi-bin/message/custom/send"
        # access_token = '49_k_WmrQuoIxcJH7eysFRG3Ri0kknRQEbUVZOMrApGclUC-MvuWbRW_LB2_eo2XC-PYTUrjKrx4-pxm-79Y3aK8NcsPCeNQLnord8ADQ6lEnnkUb89TAVSE9HQpXZepp0NG69QJzDi107ToMyuPYXbABACLK'
        querystring = {"access_token": self.get_grant_token_wx()}
        # querystring = {"access_token": access_token}
        payload = (
                "{\"touser\": \"%s\", \"msgtype\": \"text\",  \"text\": {\"content\": \"%s\" }}" % (openid, content)).\
            encode('utf-8')
        headers = {
            'Content-Type': "application/json",
            'Cache-Control': "no-cache",
            'Postman-Token': "3a32082a-0052-5591-5a7e-bf815defb396"
        }

        response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
        logger.info(response.json())
        return response.json()


    def send_photo(self, media_path, openid):
        try:
            access_token = self.get_grant_token_wx()
            # access_token = '49_nnz6lgxTqcfkbMhNqgtdbDOPDobtrekEbtQNC5XmC9K3EWxc7Pq24zkGL73jTULFUKTesumIL3hAz8UDRGLJ4cM_zQEUK5UzdqLKTpKcFtUy3FnBOPt91B5DpJ9_GVLvtphLrVWZsNpD5go2LCHaAAAULQ'
            # 如果不存在media_id，则调取微信api获取，并将media_id缓存到redis，设置过期时间为3天
            logger.info(access_token)
            with open(media_path, "rb") as upload_media_file:
                url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s" % (access_token, "image")
                urllib3.disable_warnings()
                logger.info("%"* 50)
                res = requests.post(url, files={"media": upload_media_file})
                media_id = res.json().get('media_id', 'error_occur')
            url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s' % access_token
            data = {
                "touser": openid,
                "msgtype": "image",
                "image": {
                    "media_id": media_id
                }
            }
            # p = Pool(processes=2)
            # p.apply_async(send_images_by_wx, args=(url, data))
            result = send_images_by_wx(url, data)
            # p.close()
            logger.info("+" * 50)
        except exceptions as e:
            logger.info(e)
        return

WxInterfaceUtil = WxInterface()
# print(WxInterfaceUtil.get_grant_token())

